﻿#include "record_task.h"
#include "record_set.h"

CRecord_task::CRecord_task(int ch)
{
	m_channel = ch;
}

CRecord_task::~CRecord_task()
{
}


int CRecord_task::Run()
{
	int ret = 0;
	CRecordSet * pTask     = g_pRecSet;
	uchar_t   *  pframeBuf = NULL;
	int          frameSize = 0;
	int ch                 = 0;
	static int GET_COUNT  = 50;
	int getCount		  = -200;	//首次进入线程，快速取出缓冲中的数据

	CFile_manager_arr * pIndexSet = pTask->GetIndexSet();
	CRecordSet::RECORD_CTL_PARAM  *pRecCtrl  = pTask->GetParmCtrl(ch);// &m_vecRecParam[ch];;
	if(pTask->m_bThreadLive)
	{
		TRACE_ERR("Thread is running.\n");
		return 0;

	}

	pTask->m_bThreadLive = true;

	TRACE("Thread ID %d  Start DataProcThread. Record index leaf %d .\r\nStart diskNO %d.Start Index %d \n",
		pTask->GetThreadID(),pIndexSet->GetLeafFileNum(),ret,pIndexSet->GetCurDiskNO());
	//等待一会儿
	pframeBuf = new uchar_t[m_buf_sz];

	TRACE_ERR(" ch %d Record thread GetLeafFileNum %d  .\n",m_channel,pIndexSet->GetLeafFileNum());
	while(true)
	{
		//处理磁盘录像录满的情况
		if( !pTask->IsCyCleRec()			 &&	//没有开启循环录像
			pTask->m_recStatusBIT == 0	     && //所有通道均停止录像
			pIndexSet->GetFreeSpaceMB() == 0)  //没有了录像文件
		{
			while (true)
			{
				if(pTask->IsCyCleRec())				//开启了循环录像
				{
					break;
				}
				if(pIndexSet->GetFreeSpaceMB() > 0) //又扫描到录像文件
				{
					break;
				}
				if(pTask->IsNeedStop())
				{
					break;
				}
				CrossSleep(1500);
			}
		}

		if(pTask->IsNeedStop())
		{
			pTask->StopProc();
			break;
		}

		ch = m_channel;
		while(getCount++ <= GET_COUNT) //加速获取数据
		{
			if(pTask->IsNeedStop())
			{
				TRACE_ERR("Start go out of the record loop.\n");
				break;
			}

			//加速取空数据

			if(!pTask->IsOpenManualRecord(ch))
			{
				continue;
			}

			//不满足录像的条件
			if((ret = pTask->IsContentRecord(ch)) < 0)
			{
				continue;
			}

			ret =  pTask->GetOneFrameData(ch,pframeBuf,m_buf_sz);
			if(ret <= 0)
			{
				CrossSleep(50); //获取不到数据延时一会
				continue;
			}

			if(ret > 0)
			{
				pRecCtrl->inStatus = STREAM_GETDATA;
				frameSize = ret;
				ret = pTask->WriteOneFrameData(ch,frameSize);

				if(ret < 0)
				{
					if(ERR_NOT_KEY_FRAME_1STVEDIO == ret)
					{
						continue;
					}
				}
				else
				{
					//没有取到数据流
					if(pTask->IsChReocrding(ch))
					{
						continue;
					}
					else
					{
						pRecCtrl->inStatus = STREAM_DATALOST;
					}
				}
			}
		}
		getCount = 0;

	}

	if( NULL != pframeBuf)
	{
		delete [] pframeBuf;
		pframeBuf = NULL;
	}

	pTask->m_bThreadLive = false;
	TRACE_ERR("End DataProcThread.\n");
	return 0;
}